#!/usr/bin/env bash
# vim:fdm=marker fmr=[[[,]]] cms=\ #%s

get_cnfg()
{ #[[[
    local cnfg=$1
    local section=$2
    local entry=$3

    local res=$(awk '
{
    if($0 ~ /^ *\[.*\] *$/)
    {
        if(in_section)
        {
            exit;
        }
        gsub("^ *\\[", "");
        gsub("\\] *$", "");
        #print;
        if($0 == "'$section'")
        {
            #print;
            in_section=1;
        }
        next;
    }
    if(in_section)
    {
        if($0 ~ /^ *'$entry' *=/)
        {
            split($0, arr, "=");
            print arr[2];
            exit;
        }
    }
}
' $cnfg)
    if [[ -z $res ]]
    then
        echo ''
    fi
    echo $res
} #]]]

main()
{ #[[[
    local cnfg=../server.cnfg
    if [[ ! -r $cnfg ]]
    then
        echo "cnfg not readable"
        return 1 
    fi
    local db
    db=$(get_cnfg $cnfg DB LOCATION)
    db=$(basename $db)
    if [[ -z $db ]]
    then
        echo "cnfg entry not found"
        return 1
    fi
    echo "Database: $db"

    sqlite3 $db <<!
drop table db_passwd;
create table db_passwd (name char(30),user char(30),passwd char(30));
create unique index db_passwd_x00 on db_passwd(name,user);
insert into db_passwd values('db1','dbuser','dbuser');
insert into db_passwd values('db2','dbuser','dbuser');

drop table private_key_passwd;
create table private_key_passwd(passwd char(30));
insert into private_key_passwd values('11111111');

drop table user_passwd_key;
create table user_passwd_key(key char(30));
insert into user_passwd_key values('11111111');
!

    return 0
} #]]]

main
exit $?
